package com.fm.financemanage.controller;

import com.alibaba.fastjson.JSONObject;
import com.fm.financemanage.component.RedisComponent;
import com.fm.financemanage.component.TokenComponent;
import com.fm.financemanage.constant.RedisKeyEnum;
import com.fm.financemanage.constant.ResponseEnum;
import com.fm.financemanage.exception.ParameterException;
import com.fm.financemanage.model.vo.UserInfoVo;
import com.fm.financemanage.model.vo.UserTokenVo;
import com.fm.financemanage.model.vo.simcard.SimCardOpeartorVo;
import com.fm.financemanage.response.Callback;
import com.fm.financemanage.response.JsonData;
import com.fm.financemanage.service.SimCardService;
import com.fm.financemanage.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequestMapping("/user")
@Api(tags = "sim卡")
@RestController
@Validated
public class UserApi {


    @Autowired
    private UserService userService;

    @Autowired
    private TokenComponent tokenComponent;

    @Autowired
    private RedisComponent redisComponent;


    @PostMapping("/login")
    @ApiOperation("")
    public JsonData login(HttpServletRequest request, HttpServletResponse response,
                          @ApiParam(name = "account", value = "account", required = true)
                          @RequestParam(name = "account", required = false) String account,
                          @ApiParam(name = "password", value = "password", required = true)
                          @RequestParam(name = "password", required = false) String password,
                          @ApiParam(name = "companyKey", value = "公司key(填写这个就是会计登录)", required = true)
                          @RequestParam(name = "companyKey", required = false) String companyKey

    ) {


        final UserInfoVo infoVo = userService.login(account, password, companyKey);
        final String token = tokenComponent.getByUser(infoVo);
        redisComponent.setExTimeValue(RedisKeyEnum.user_tokens.getName() + token, JSONObject.toJSONString(infoVo.getUserTokenVo()), RedisKeyEnum.user_tokens.getTimeSeconds());
        response.setHeader("Authorization", token);
        return Callback.success(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMemo(), infoVo);
    }
}
